import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { hasPermission, getDefaultRedirectPath } from '@/utils/auth'

// 前台路由
const frontendRoutes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: () => import('@/views/frontend/HomeView.vue'),
    meta: { title: '首页' }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/frontend/LoginView.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('@/views/frontend/RegisterView.vue'),
    meta: { title: '注册' }
  },
  {
    path: '/products',
    name: 'products',
    component: () => import('@/views/frontend/ProductsView.vue'),
    meta: { title: '商品列表' }
  },
  {
    path: '/product/:id',
    name: 'product-detail',
    component: () => import('@/views/frontend/ProductDetailView.vue'),
    meta: { title: '商品详情' }
  },
  {
    path: '/user',
    name: 'user-center',
    component: () => import('@/views/frontend/UserCenterView.vue'),
    meta: { title: '个人中心', requiresAuth: true },
    children: [
      {
        path: 'profile',
        name: 'user-profile',
        component: () => import('@/views/frontend/user/ProfileView.vue'),
        meta: { title: '个人信息' }
      },
      {
        path: 'products',
        name: 'user-products',
        component: () => import('@/views/frontend/user/MyProductsView.vue'),
        meta: { title: '我的商品' }
      },
      {
        path: 'favorites',
        name: 'user-favorites',
        component: () => import('@/views/frontend/user/FavoritesView.vue'),
        meta: { title: '我的收藏' }
      },
      {
        path: 'history',
        name: 'user-history',
        component: () => import('@/views/frontend/user/HistoryView.vue'),
        meta: { title: '浏览历史' }
      },
      {
        path: 'orders',
        name: 'user-orders',
        component: () => import('@/views/frontend/user/OrdersView.vue'),
        meta: { title: '我的订单' }
      },
      {
        path: 'messages',
        name: 'user-messages',
        component: () => import('@/views/frontend/user/MessagesView.vue'),
        meta: { title: '我的消息' }
      }
    ]
  },
  {
    path: '/publish',
    name: 'publish',
    component: () => import('@/views/frontend/PublishView.vue'),
    meta: { title: '发布商品', requiresAuth: true }
  },
  {
    path: '/edit/:id',
    name: 'edit-product',
    component: () => import('@/views/frontend/EditProductView.vue'),
    meta: { title: '编辑商品', requiresAuth: true }
  },
  {
    path: '/payment',
    name: 'payment',
    component: () => import('@/views/frontend/PaymentView.vue'),
    meta: { title: '支付确认', requiresAuth: true }
  }
]

// 后台路由
const adminRoutes: Array<RouteRecordRaw> = [
  {
    path: '/admin',
    name: 'admin',
    component: () => import('@/views/admin/AdminLayout.vue'),
    meta: { title: '后台管理', requiresAuth: true, requiresAdmin: true },
    children: [
      {
        path: '',
        name: 'admin-dashboard',
        component: () => import('@/views/admin/DashboardView.vue'),
        meta: { title: '仪表盘' }
      },
      {
        path: 'users',
        name: 'admin-users',
        component: () => import('@/views/admin/UsersView.vue'),
        meta: { title: '用户管理' }
      },
      {
        path: 'products',
        name: 'admin-products',
        component: () => import('@/views/admin/ProductsView.vue'),
        meta: { title: '商品管理' }
      },
      {
        path: 'orders',
        name: 'admin-orders',
        component: () => import('@/views/admin/OrdersView.vue'),
        meta: { title: '订单管理' }
      },
      {
        path: 'categories',
        name: 'admin-categories',
        component: () => import('@/views/admin/CategoriesView.vue'),
        meta: { title: '分类管理' }
      },
      {
        path: 'messages',
        name: 'admin-messages',
        component: () => import('@/views/admin/MessagesView.vue'),
        meta: { title: '消息管理' }
      },
      {
        path: 'actions',
        name: 'admin-actions',
        component: () => import('@/views/admin/ActionsView.vue'),
        meta: { title: '互动管理' }
      },
      {
        path: 'comments',
        name: 'admin-comments',
        component: () => import('@/views/admin/CommentsView.vue'),
        meta: { title: '评论管理' }
      }
    ]
  }
]

const routes: Array<RouteRecordRaw> = [
  ...frontendRoutes,
  ...adminRoutes,
  {
    path: '/:pathMatch(.*)*',
    name: 'not-found',
    component: () => import('@/views/NotFoundView.vue'),
    meta: { title: '页面不存在' }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  
  // 设置页面标题
  document.title = to.meta?.title ? `${to.meta.title} - 二手交易平台` : '二手交易平台'
  
  // 初始化用户信息
  await userStore.initUserInfo()
  
  // 检查是否需要登录
  if (to.meta?.requiresAuth && !userStore.isLoggedIn) {
    // 保存当前路径作为重定向地址
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
    return
  }
  
  // 检查是否需要管理员权限
  if (to.meta?.requiresAdmin && !hasPermission(userStore.user, true)) {
    ElMessage.error('您没有访问该页面的权限')
    next('/')
    return
  }
  
  // 已登录用户访问登录页面，根据角色重定向
  if (to.path === '/login' && userStore.isLoggedIn) {
    const defaultPath = getDefaultRedirectPath(userStore.user?.userRole || 1)
    next(defaultPath)
    return
  }
  
  next()
})

export default router
